﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Compression;
using System.IO;

namespace Common.Compression
{
    public static class DeflateHelper
    {
        /// <summary>
        /// Compresses data using Deflate format
        /// </summary>
        /// <param name="RawData">A byte array that you want to be compressed.</param>
        /// <returns>Compressed bytes</returns>
        public static byte[] Compress(byte[] RawData)
        {
            if (RawData.isNull() || RawData.Length < 1)
                throw new ArgumentNullException("RawData");

            using (MemoryStream ms = new MemoryStream())
            {
                using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress))
                {
                    ds.Write(RawData, 0, RawData.Length);
                }
                return ms.ToArray();
            }
        }

        /// <summary>
        /// Decompresses deflate data to original data.
        /// Note :For some reason this function doesnt not work all the time... Unknown reason at this time...
        /// </summary>
        /// <param name="RawData">Compress deflate data</param>
        /// <returns>Original uncompressed data</returns>
        public static byte[] Decompress(byte[] RawData)
        {
            if (RawData.isNull() || RawData.Length < 1)
                throw new ArgumentNullException("RawData");

            using (MemoryStream dcmpData = new MemoryStream())
            {
                using (MemoryStream ms = new MemoryStream(RawData))
                {
                    using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress))
                    {
                        ds.CopyTo(dcmpData);
                    }
                }

                return dcmpData.ToArray();
            }
        }
    }
}
